package com.stormrage.edu.ctrl.edu;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduVideoServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduVideo;
import com.stormrage.entity.edu.req.EduVideoReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;
import com.stormragetech.core.entity.UploadVideoRep;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @Title: EduVideoCtrl.java
 * @Package com.stormrage.edu.ctrl
 * @Description: 课件 Controller
 * @author www.stormragetech.com
 * @date 2016年4月11日
 * @version V1.0
 */
@Controller
@RequestMapping("/video")
public class EduVideoCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EduVideoCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.video']}")
	private String videoPath;

	@Value("#{constants['path.thumb']}")
	private String thumbPath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduVideoServ eduVideoServ;

	@RequiresPermissions("video:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 fileCreate 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 fileCreate 】-【 GET 】- 结束运行 ");
		return "edu/video/create/file";

	}

	@RequiresPermissions("video:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, EduVideo entity,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 create 】-【 POST 】- 开始运行 ");

		logger.debug(" 视频名称为 " + entity.getVideo());

		ErrorRep err = null;
		String errMsg = "";

		if (null == file || file.isEmpty()) {

			StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "视频文件不能为空",
					StormrageTechException.ERR_APP, "【 EduVideoCtrl 】-【 create 】");

			err = ErrorRep.instance(false, exception.getMessage());
			redirect.addFlashAttribute("err", err);

			return "redirect:/video/create";

		}

		try {

			UploadVideoRep rep = eduVideoServ.upload(file, rootPath);
			entity.setThumb(rep.getName() + ".jpg");
			entity.setUrl(rep.getName() + ".mp4");
			entity.setVideoLen(rep.getLen());

			// ------------------ Ctrl操作 ------------------

			eduVideoServ.create(entity);
			errMsg = "提示信息：添加课件成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加课件失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/video/list";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 create 】-【 POST 】- 结束运行 ");
		return "redirect:/video/list";

	}

	@RequiresPermissions("video:create")
	@RequestMapping(value = "/create/name", method = RequestMethod.GET)
	public String nameCreate(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 GET 】- 结束运行 ");
		return "edu/video/create/name";

	}

	@RequiresPermissions("video:create")
	@RequestMapping(value = "/create/name", method = RequestMethod.POST)
	public String nameCreate(@CurrentUser ShiroAcct curr, EduVideo entity,
			@RequestParam(value = "name", required = false) String name, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 POST 】- 开始运行 ");

		logger.debug(" 视频名称为 " + entity.getVideo());

		ErrorRep err = null;
		String errMsg = "";

		try {

			UploadVideoRep rep = eduVideoServ.upload(name + ".mp4", rootPath);
			entity.setThumb(rep.getName() + ".jpg");
			entity.setUrl(rep.getName() + ".mp4");
			entity.setVideoLen(rep.getLen());

			// ------------------ Ctrl操作 ------------------

			eduVideoServ.create(entity);
			errMsg = "提示信息：添加课件成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加课件失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/video/list";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 POST 】- 结束运行 ");
		return "redirect:/video/list";

	}

	@RequiresPermissions("video:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduVideo entity = eduVideoServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/video/edit";

	}

	@RequiresPermissions("video:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, EduVideo req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		logger.debug(" edit请求为 " + req.toString());

		try {

			// ------------------ Ctrl操作 ------------------
			eduVideoServ.update(req);
			errMsg = "提示信息：修改课件成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改课件失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/video/list";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/video/list";

	}

	@RequiresPermissions("video:edit")
	@RequestMapping(value = "/thumb/{id}", method = RequestMethod.GET)
	public String thumb(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 thumb 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 thumb 】-【 GET 】- 结束运行 ");
		return "edu/video/thumb";

	}

	@RequiresPermissions("video:edit")
	@RequestMapping(value = "/thumb/{id}", method = RequestMethod.POST)
	public String thumb(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id,
			@RequestParam(value = "time", required = true) Integer time, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 thumb 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduVideoServ.editThumb(id, time, rootPath);
			errMsg = "提示信息：修改课件缩略图成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改课件缩略图失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/video/list";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 thumb 】-【 POST 】- 结束运行 ");
		return "redirect:/video/list";

	}

	@RequiresPermissions("video:edit")
	@RequestMapping(value = "/upload/{id}", method = RequestMethod.GET)
	public String uplaod(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 GET 】- 结束运行 ");
		return "edu/video/upload";

	}

	@RequiresPermissions("video:edit")
	@RequestMapping(value = "/upload/{id}", method = RequestMethod.POST)
	public String upload(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id,
			@RequestParam(value = "name", required = false) String name, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			UploadVideoRep rep = eduVideoServ.upload(name + ".mp4", rootPath);

			EduVideo entity = eduVideoServ.queryById(id);
			entity.setThumb(rep.getName() + ".jpg");
			entity.setUrl(rep.getName() + ".mp4");
			entity.setVideoLen(rep.getLen());

			// ------------------ Ctrl操作 ------------------

			eduVideoServ.updateVideo(entity);
			errMsg = "提示信息：修改课件成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改课件失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/video/list";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 nameCreate 】-【 POST 】- 结束运行 ");
		return "redirect:/video/list";

	}

	@RequiresPermissions("video:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduVideoServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/video/list";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/video/list";

	}

	@RequiresPermissions("video:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, EduVideoReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduVideoCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "edu/video/list";
	}

	@RequiresPermissions("video:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EduVideoReq req) {

		logger.debug(" 【 Controller 】- 【 EduVideoCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + req.toString());

			ListRep entity = eduVideoServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduVideoCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
	public String video(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model)
			throws UnsupportedEncodingException {

		logger.debug("【 Controller 】-【 LeaStudyCtrl 】-【 video 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Controller 操作 ------------------
			EduVideo entity = eduVideoServ.queryById(id);
			
			// ------------------ Model 赋值 ------------------
			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("vpath", rootUrl + videoPath);
			model.addAttribute("tpath", rootUrl + thumbPath);
			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug("【 Controller 】-【 LeaStudyCtrl 】-【 video 】-【 GET 】-【 COMPLETED 】");
		return "edu/video/video";
	}

}
